import logging
from eshop.lib.base import *

log = logging.getLogger(__name__)

class ProductController(BaseController):

    def __call__(self, environ, start_response):
        return BaseController.__call__(self, environ, start_response)     
   
    def add(self):
        c.category = model.ProductCategory.q.get(request.params.get('category_id'))
        c.brands = model.Brand.q.all()
        return render('/catalog/product_add.mako')
    
    def delete(self, id):
        product = model.Product.q.get(id)
        product.delete()
        redirect_to(controller='category', action='view', id=product.category.id)
    
    def edit (self, id):
        c.product = model.Product.q.get(id)
        c.brands = model.Brand.q.all()
        return render('/catalog/product_edit.mako')

    def index(self):
        c.products = model.Product.q.all()
        return render('/catalog/product_list.mako')
    
    def view (self, id=None):
        c.product = model.Product.q.get(id)
        return render('/catalog/product_view.mako')
    
    def view_by_mapping (self, url_mapping):
        c.product = model.Product.q.filter_by(url_mapping=url_mapping).first()
        if c.product:
            return render('/catalog/product_view.mako')
        else:
            #TODO handle as 404
            return self.index()

    def save_edit(self, id):
        product = model.Product.q.get(id)
        self.__populate_product(product, request)
        redirect_to(controller='category', action='view', id=product.category.id)
        
    def save_add(self):
        product = model.Product(id=None)
        product.root_comment = model.Comment(id=None)
        product.category = model.ProductCategory.q.get(request.params.get('category_id'))
        self.__populate_product(product, request)
        self.__save_product_mapping(product)
        redirect_to(controller='category', action='view', id=product.category.id)
    
    def __save_product_mapping(self, product):
        url_mapping = sanitize_name_to_url(product.name)
        products = model.Product.q.get_by(url_mapping=url_mapping)
        if products:
            model.flush_all()
            url_mapping += '_' + str(product.id)
        product.url_mapping = url_mapping  
        
    def __populate_product(self, product, request):
        product.name = request.params.get('name')
        product.description = request.params.get('description')
        product.brand = model.Brand.q.get(request.params.get('brand_id'))
        if product.id == None:
            product.url_mapping = '$' + product.name # temp hack to persist entity  
        product.properties = {}
        for k, v in request.params.iteritems():
            if k.startswith('$prop.'):
                product.properties[k[6:]] = v
        
        main_image_file = request.POST['main_image']
        if main_image_file != None:
#            print 'Successfully uploaded: %s, size: %i' % \
#                (main_image_file.filename, len(main_image_file.value)) 
            old_image = product.main_image
            main_image = model.Image(file_name=main_image_file.filename);
            product.main_image = main_image
            model.flush_all()
            if old_image != None:
                old_image.delete()
                try:
                    g.image_storage.delete(old_image.id, old_image.file_name)
                except:
                    log(e)
            g.image_storage.save(main_image_file.file, main_image.id, main_image.file_name)
        
